<template>
  <view class="container">
    <view class="header">
      <text class="title">编辑就诊信息</text>
    </view>
    
    <view v-if="loading" class="loading">加载中...</view>
    
    <FormView
      v-else
      :field-config="fieldConfig"
      :form="form"
      :show-buttons="true"
      @submit="handleSubmit"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { request } from '@/service/request'
import FormView from '@/components/FormView.vue'
import { healthSeeDocFields } from './fields'
import { localStg } from '@/utils'

const fieldConfig = healthSeeDocFields
const loading = ref(false)

const form = reactive({
  name: '',
  idNumber: '',
  recordid: '',
})

onMounted(() => {
  const obj = localStg.get("demographicInfo");
  // obj
  if(obj){
    form.name = obj.name;
    form.idNumber = obj.idNumber;
    form.recordid = obj.recordid;
  }
  loadRecord()
})

// onMounted(() => {
//   loadRecord()
// })
async function loadRecord() {
  const pages = Taro.getCurrentInstance()?.router?.params
  const id = pages?.id
  
  // if (!id) {
  //   Taro.showToast({ title: '参数错误', icon: 'error' })
  //   Taro.navigateBack()
  //   return
  // }
  
  loading.value = true
  try {
    const result = await request.get(`/health_records/health_seedoc/healthSeeDocInfo/queryById?id=${id}`, {}, {
      useErrMsg: true
    })

    // result
    
    if (result.success) {
      Object.assign(form, result.success)
    }
  } catch (error) {
    // 加载数据失败
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  } finally {
    loading.value = false
  }
}

async function handleSubmit(formData: any) {
  try {
    await request.put('/health_records/health_seedoc/healthSeeDocInfo/edit', formData, {
      useErrMsg: true
    })
    
    Taro.showToast({ title: '更新成功', icon: 'success' })
    
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500)
  } catch (error) {
    // 更新失败
    Taro.showToast({ title: '更新失败', icon: 'error' })
  }
}
</script>

<style scoped>
.container {
  padding: 32rpx;
  background: #f6f8fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 40rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #2563eb;
}

.loading {
  text-align: center;
  padding: 100rpx 0;
  color: #6b7280;
}
</style>
